import type { AxiosRequestConfig, AxiosResponse } from 'axios'
import request from 'utils/request'

import userApi from './api/user'

type ApiKeys = keyof typeof userApi

// 默认API前缀
const apiPrefix = '/api'
const APIs = [
  { prefix: apiPrefix, data: userApi },
  // { prefix: '/test', data: test },
]

interface StandardResponse<R> {
  code: number
  data: R
  headers?: any
  msg?: string
  status?: string
}

type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE'
export type AxiosFunc = <Res = any, T = any>(
  params?: T,
  options?: AxiosRequestConfig
) => Promise<StandardResponse<Res>>

const gen = (params: string, prefix: string): AxiosFunc => {
  let url = prefix + params
  let method: HttpMethod = 'GET'

  const paramsArray = params.split(' ')
  if (paramsArray.length === 2) {
    method = paramsArray[0].toUpperCase() as HttpMethod
    url = prefix + paramsArray[1]
  }

  if (method === 'GET' || method === 'DELETE') {
    return async function (params, options = {}) {
      const res = await request({
        url,
        params,
        method,
        ...options,
      })
      return res.data as StandardResponse<any>
    }
  }

  return async function (data, options = {}) {
    const res = await request({
      url,
      data,
      method,
      ...options,
    })
    return res.data as StandardResponse<any>
  }
}

const APIFunction: Record<ApiKeys, AxiosFunc> = {} as any

APIs.forEach(({ data, prefix }) => {
  Object.keys(data).forEach((key) => {
    APIFunction[key as ApiKeys] = gen(data[key as keyof typeof data], prefix)
  })
})

export default APIFunction
